<template>
  <div class="radar-chart-container">
    <div ref="radarChart" class="radar-chart"></div>
    <div v-if="loading" class="chart-loading">
      <i class="el-icon-loading"></i>
      <p>加载中...</p>
    </div>
    <div v-if="error" class="chart-error">
      <i class="el-icon-warning"></i>
      <p>{{ error }}</p>
    </div>
  </div>
</template>

<script>
import echarts from 'echarts'

export default {
  name: 'StudentRadarChart',
  props: {
    studentNum: {
      type: String,
      default: ''
    },
    termId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      chart: null,
      loading: true,
      error: null,
      studentData: null,
      chartColors: {
        main: {
          lineColor: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {offset: 0, color: '#FF3CAC'},
              {offset: 0.5, color: '#784BA0'},
              {offset: 1, color: '#2B86C5'}
            ]
          },
          areaColor: new echarts.graphic.RadialGradient(0.5, 0.5, 0.5, [
            {offset: 0, color: 'rgba(255, 60, 172, 0.5)'},
            {offset: 0.5, color: 'rgba(120, 75, 160, 0.3)'},
            {offset: 1, color: 'rgba(43, 134, 197, 0.1)'}
          ])
        },
        average: {
          lineColor: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {offset: 0, color: '#00F5A0'},
              {offset: 1, color: '#00D9F5'}
            ]
          },
          areaColor: new echarts.graphic.RadialGradient(0.5, 0.5, 0.5, [
            {offset: 0, color: 'rgba(0, 245, 160, 0.3)'},
            {offset: 1, color: 'rgba(0, 217, 245, 0.1)'}
          ])
        }
      }
    }
  },
  watch: {
    studentNum: {
      handler(val) {
        if (val && this.termId) {
          this.fetchStudentData();
        }
      },
      immediate: true
    },
    termId: {
      handler(val) {
        if (val && this.studentNum) {
          this.fetchStudentData();
        }
      },
      immediate: true
    }
  },
  methods: {
    async fetchStudentData() {
      if (!this.studentNum || !this.termId) return;
      
      this.loading = true;
      this.error = null;
      
      try {
        // 获取综合成绩数据
        const params = { studentNum: this.studentNum, termId: this.termId };
        
        // 使用findPage方法替代findByName
        const pageRequest = {
          pageNum: 1,
          pageSize: 10,
          params: [
            { name: 'studentNum', value: this.studentNum },
            { name: 'termId', value: this.termId }
          ]
        };
        
        const res = await this.$api.busSynthesis.findPage(pageRequest);
        
        if (res.code === 200 && res.data && res.data.content && res.data.content.length > 0) {
          this.studentData = res.data.content[0];
          await this.initChart();
        } else {
          this.error = '未找到学生成绩数据';
        }
      } catch (error) {
        console.error('获取学生成绩数据失败:', error);
        this.error = '获取数据失败，请稍后再试';
      } finally {
        this.loading = false;
      }
    },
    
    async initChart() {
      if (!this.studentData) return;
      
      // 如果图表已经存在，先销毁
      if (this.chart) {
        this.chart.dispose();
      }
      
      // 初始化图表
      this.chart = echarts.init(this.$refs.radarChart);
      
      // 准备数据
      const data = await this.prepareChartData();
      
      // 设置图表选项
      const option = {
        backgroundColor: {
          type: 'radial',
          x: 0.5,
          y: 0.5,
          r: 0.5,
          colorStops: [
            {offset: 0, color: '#f7f8fa'},
            {offset: 1, color: '#e6ebf5'}
          ]
        },
        title: {
          text: '学生成绩五边形战士图',
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold',
            color: '#333',
            textShadow: '1px 1px 2px rgba(0,0,0,0.1)'
          },
          left: 'center',
          top: 10
        },
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            return params.name + '<br/>' + 
                   params.marker + params.seriesName + ': ' + params.value;
          }
        },
        legend: {
          data: ['个人成绩', '班级平均'],
          bottom: '5%',
          icon: 'circle'
        },
        radar: {
          shape: 'polygon',
          center: ['50%', '55%'],
          radius: '60%',
          nameGap: 15,
          splitNumber: 4,
          axisName: {
            color: '#333',
            fontSize: 14,
            fontWeight: 'bold',
            formatter: function(name) {
              return '{a|' + name + '}';
            },
            rich: {
              a: {
                color: '#333',
                fontSize: 14,
                fontWeight: 'bold',
                lineHeight: 20,
                align: 'center'
              }
            }
          },
          indicator: data.indicators,
          splitArea: {
            areaStyle: {
              color: ['rgba(255,255,255,0.8)', 'rgba(220,240,255,0.4)', 'rgba(200,230,255,0.3)', 'rgba(180,220,255,0.2)']
            }
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(120, 140, 180, 0.8)'
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(120, 140, 180, 0.6)',
              width: 1.5
            }
          }
        },
        series: [
          {
            name: '个人成绩',
            type: 'radar',
            emphasis: {
              lineStyle: {
                width: 4
              }
            },
            data: [
              {
                value: data.studentValues,
                name: '个人成绩',
                symbolSize: 8,
                symbol: 'circle',
                itemStyle: {
                  color: '#FF3CAC'
                },
                lineStyle: {
                  color: this.chartColors.main.lineColor,
                  width: 3,
                  shadowColor: 'rgba(0, 0, 0, 0.3)',
                  shadowBlur: 10,
                  shadowOffsetY: 5
                },
                areaStyle: {
                  color: this.chartColors.main.areaColor,
                  opacity: 0.8
                }
              }
            ]
          },
          {
            name: '班级平均',
            type: 'radar',
            emphasis: {
              lineStyle: {
                width: 4
              }
            },
            data: [
              {
                value: data.averageValues,
                name: '班级平均',
                symbolSize: 6,
                symbol: 'circle',
                itemStyle: {
                  color: '#00F5A0'
                },
                lineStyle: {
                  color: this.chartColors.average.lineColor,
                  width: 2
                },
                areaStyle: {
                  color: this.chartColors.average.areaColor,
                  opacity: 0.6
                }
              }
            ]
          }
        ]
      };
      
      // 应用图表选项
      this.chart.setOption(option);
      
      // 响应窗口大小变化
      window.addEventListener('resize', this.resizeChart);
    },
    
    async prepareChartData() {
      // 准备雷达图的指标和数据
      const indicators = [
        { name: '德育成绩', max: 100 },
        { name: '智育成绩', max: 100 },
        { name: '体育成绩', max: 100 },
        { name: '扩展成绩', max: 100 },
        { name: '心理测评', max: 100 }
      ];
      
      // 获取心理测评成绩
      const psyScore = await this.getPsyScore();
      
      // 从学生数据中提取成绩值
      const studentValues = [
        this.studentData.moralTotal || 0,
        this.studentData.intellectualTotal || 0,
        this.studentData.sportTotal || 0,
        this.studentData.expandTotal || 0,
        psyScore || 0
      ];
      
      // 模拟班级平均值（实际应用中应从API获取）
      const averageValues = [
        85, 80, 75, 70, 90
      ];
      
      return {
        indicators,
        studentValues,
        averageValues
      };
    },
    
    getPsyScore() {
      // 这里应该调用API获取心理测评成绩
      return new Promise((resolve, reject) => {
        // 使用findPage方法替代findByStudentAndTerm
        const pageRequest = {
          pageNum: 1,
          pageSize: 10,
          params: [
            { name: 'studentNum', value: this.studentNum },
            { name: 'termId', value: this.termId }
          ]
        };
        
        this.$api.psyScore.findPage(pageRequest).then(res => {
          if (res.code === 200 && res.data && res.data.content && res.data.content.length > 0) {
            resolve(res.data.content[0].totalScore || 0);
          } else {
            resolve(0);
          }
        }).catch(error => {
          console.error('获取心理测评成绩失败:', error);
          resolve(0);
        });
      });
    },
    
    resizeChart() {
      if (this.chart) {
        this.chart.resize();
      }
    }
  },
  mounted() {
    if (this.studentNum && this.termId) {
      this.fetchStudentData();
    } else {
      this.loading = false;
      this.error = '请提供学生学号和学期ID';
    }
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
    window.removeEventListener('resize', this.resizeChart);
  }
}
</script>

<style scoped>
.radar-chart-container {
  position: relative;
  width: 100%;
  height: 400px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  transition: all 0.3s ease;
  padding: 10px;
}

.radar-chart-container:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
}

.radar-chart {
  width: 100%;
  height: 100%;
  border-radius: 8px;
}

.chart-loading, .chart-error {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 10;
  backdrop-filter: blur(5px);
  -webkit-backdrop-filter: blur(5px);
}

.chart-loading i, .chart-error i {
  font-size: 40px;
  margin-bottom: 15px;
  animation: pulse 1.5s infinite ease-in-out;
}

.chart-error {
  color: #F56C6C;
}

.chart-loading {
  color: #409EFF;
}

@keyframes pulse {
  0% {
    transform: scale(0.95);
    opacity: 0.7;
  }
  50% {
    transform: scale(1.05);
    opacity: 1;
  }
  100% {
    transform: scale(0.95);
    opacity: 0.7;
  }
}
</style> 